<template>
  <el-dialog
    :model-value="modelValue"
    title="订单支付"
    width="90%"
    top="5vh"
    :close-on-click-modal="false"
    :show-close="false"
    @update:modelValue="$emit('update:modelValue', $event)"
    @close="handleClose"
  >
    <div class="payment-container">
      <!-- 地址选择部分 -->
      <div class="address-section" @click="showAddressList = true">
        <div class="address-header">
          <span class="title">收货地址</span>
          <el-icon><ArrowRight /></el-icon>
        </div>
        <div v-if="selectedAddress" class="address-content">
          <div class="address-info">
            <span class="receiver">{{ selectedAddress.receiverName }}</span>
            <span class="phone">{{ selectedAddress.receiverMobile }}</span>
            <el-tag v-if="selectedAddress.isDefault" size="small" type="danger">默认</el-tag>
          </div>
          <div class="address-detail">
            {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}
          </div>
        </div>
        <div v-else class="address-empty">
          <el-text type="danger">请选择收货地址</el-text>
        </div>
      </div>

      <!-- 订单信息部分 -->
      <div class="order-section">
        <div class="order-header">订单信息</div>
        <div class="order-items">
          <div v-for="item in orderItems" :key="item.productId" class="order-item">
            <div class="item-name">{{ item.productName }}</div>
            <div class="item-price">¥{{ item.price }} × {{ item.quantity }}</div>
          </div>
        </div>
        <div class="order-total">
          <span>合计：</span>
          <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 支付方式部分 -->
      <div class="payment-section">
        <div class="payment-header">选择支付方式</div>
        <div class="payment-methods">
          <div
            class="payment-method"
            :class="{ 'active': paymentType === 1 }"
            @click="paymentType = 1"
          >
            <div class="method-icon">
              <img src="@/assets/alipay.png" alt="支付宝">
            </div>
            <div class="method-name">支付宝</div>
          </div>
        </div>
      </div>

      <!-- 二维码显示弹窗 -->
      <el-dialog
        v-model="showQrCodeDialog"
        title="请使用支付宝扫码支付"
        width="300px"
        :close-on-click-modal="false"
      >
        <div class="qr-code-container">
          <canvas ref="qrCodeCanvas" class="qr-code-canvas"></canvas>
          <div class="qr-code-info">
            <p>订单号: {{ currentOrderId }}</p>
            <p>金额: ¥{{ currentAmount }}</p>
            <p v-if="isSandbox" class="sandbox-tip">(沙箱测试环境)</p>
          </div>
          <div class="payment-instruction">
            <p>请使用支付宝APP扫码支付</p>
            <p v-if="isSandbox">使用支付宝沙箱账号支付</p>
          </div>
        </div>
        <template #footer>
          <el-button type="primary" @click="showQrCodeDialog = false">已完成支付</el-button>
          <el-button @click="refreshQrCode" :loading="refreshingQrCode">刷新二维码</el-button>
        </template>
      </el-dialog>
    </div>

    <template #footer>
  <div class="payment-footer">
    <div class="payment-amount">
      应付：<span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
    </div>
    <div class="payment-actions">
      <el-button plain @click="handleClose">取消支付</el-button>
      <el-button
        type="primary"
        :loading="isProcessing"
        @click="handlePayment"
        :disabled="!selectedAddress || paymentType === 0 || isProcessing"
      >
        立即支付
      </el-button>
    </div>
  </div>
</template>

    <!-- 地址选择抽屉 -->
    <el-drawer
      v-model="showAddressList"
      title="选择收货地址"
      direction="btt"
      size="60%"
    >
      <div class="address-list-container">
        <div
          v-for="address in addressList"
          :key="address.addressId"
          class="address-item"
          :class="{ 'active': selectedAddress?.addressId === address.addressId }"
          @click="selectAddress(address)"
        >
          <div class="address-content">
            <div class="address-header">
              <span class="receiver">{{ address.receiverName }}</span>
              <span class="phone">{{ address.receiverMobile }}</span>
              <el-tag v-if="address.isDefault" size="small" type="danger">默认</el-tag>
            </div>
            <div class="address-detail">
              {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
            </div>
          </div>
          <el-icon class="check-icon" v-if="selectedAddress?.addressId === address.addressId">
            <Check />
          </el-icon>
        </div>

        <div class="address-actions">
          <el-button type="primary" @click="showAddressList = false">确认选择</el-button>
        </div>
      </div>
    </el-drawer>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ArrowRight, Check } from '@element-plus/icons-vue'
import { useAddressStore } from '@/stores/addressStore'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useOrderStore } from '@/stores/orderStore'
import { useRouter } from 'vue-router'
import QRCode from 'qrcode'
import { getPaymentQRCode, checkPaymentStatus } from '@/api/Payment';

const props = defineProps({
  modelValue: Boolean,
  orderItems: Array,
  totalAmount: Number,
  userId: String
})

const emit = defineEmits(['update:modelValue', 'payment-success'])

const router = useRouter()
const addressStore = useAddressStore()
const orderStore = useOrderStore()

const paymentType = ref(1) // 1-支付宝
const isProcessing = ref(false)
const showAddressList = ref(false)
const selectedAddress = ref(null)
const paymentStatusPolling = ref(null)
const showQrCodeDialog = ref(false)
const currentOrderId = ref('')
const currentAmount = ref('')
const qrCodeCanvas = ref(null)
const isSandbox = ref(false)
const refreshingQrCode = ref(false)

const addressList = computed(() => addressStore.addressList)

onMounted(async () => {
  await addressStore.initAddresses()
  const defaultAddress = addressList.value.find(item => item.isDefault === 1)
  if (defaultAddress) {
    selectedAddress.value = defaultAddress
  }
})

onBeforeUnmount(() => {
  if (paymentStatusPolling.value) {
    clearInterval(paymentStatusPolling.value)
  }
})

const selectAddress = (address) => {
  selectedAddress.value = address
}


const handleClose = () => {
  emit('update:modelValue', false)
}

const generateQrCode = (url) => {
  if (!qrCodeCanvas.value) return

  QRCode.toCanvas(qrCodeCanvas.value, url, {
    width: 200,
    margin: 1,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  }, (error) => {
    if (error) {
      console.error('生成二维码失败:', error)
      ElMessage.error('生成支付二维码失败')
    }
  })
}

const refreshQrCode = async () => {
  try {
    refreshingQrCode.value = true
    const response = await getPaymentQRCode({
              ordersId: currentOrderId.value,
              totalAmount: currentAmount.value,
              subject: `订单支付 - ${props.orderItems.map(item => item.productName).join(',')}`
           });
    // const response = await axios.get('https://2b15fa7cb754.ngrok-free.app/product/api/payment/qr-code', {
    //   params: {
    //     ordersId: currentOrderId.value,
    //     totalAmount: currentAmount.value,
    //     subject: `订单支付 - ${props.orderItems.map(item => item.productName).join(',')}`
    //   },
    //   // 添加请求头以跳过 ngrok 提示
    //   headers: {
    //    'ngrok-skip-browser-warning': 'true'
    //  }
    // })

    if (response.data.code === 1) {
      generateQrCode(response.data.data.qrCodeUrl)
      ElMessage.success('二维码已刷新')
    }
  } catch (error) {
    ElMessage.error('刷新二维码失败')
  } finally {
    refreshingQrCode.value = false
  }
}

const startPaymentPolling = (orderId) => {
  if (paymentStatusPolling.value) {
    clearInterval(paymentStatusPolling.value)
  }

  paymentStatusPolling.value = setInterval(async () => {
    try {
      const response = await checkPaymentStatus(orderId);
    //   const response = await axios.get(
    //     `https://2b15fa7cb754.ngrok-free.app/product/api/payment/status?orderId=${orderId}`, {
    //       // 添加请求头以跳过 ngrok 提示
    //      headers: {
    //        'ngrok-skip-browser-warning': 'true'
    //  }
    //     }
    //   )

      if (response.data.code === 1 && response.data.data?.paid) {
        clearInterval(paymentStatusPolling.value)
        showQrCodeDialog.value = false
        ElMessage.success('支付成功！')

        const cartIds = props.orderItems
          .filter(item => item.cartId)
          .map(item => item.cartId)

        if (cartIds.length > 0) {
          emit('payment-success', {
            orderId,
            cartIds
          })
        }

        emit('update:modelValue', false)
        router.push('/order/detail/' + orderId)
      }
    } catch (error) {
      console.error('支付状态查询失败:', error)
    }
  }, 3000)

  setTimeout(() => {
    if (paymentStatusPolling.value) {
      clearInterval(paymentStatusPolling.value)
      ElMessage.warning('支付状态查询超时，请检查支付是否完成')
    }
  }, 300000)
}

const handlePayment = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  try {
    isProcessing.value = true

    const subject = `订单支付 - ${props.orderItems.map(item => item.productName).join(',')}`
    const totalAmount = props.totalAmount.toFixed(2)
    const body = `购买${props.orderItems.length}件商品`

    const orderData = {
      userId: props.userId,
      addressId: selectedAddress.value.addressId,
      items: props.orderItems.map(item => {
        if (!item.cartId) {
          console.error('商品缺少 cartId:', item)
          throw new Error('商品数据不完整，无法创建订单')
        }
        return {
          productId: item.productId,
          quantity: item.quantity,
          price: item.price,
          cartId: item.cartId
        }
      })
    }

    const createOrderResponse = await orderStore.createOrder(orderData)

    if (createOrderResponse.code !== 1) {
      throw new Error(createOrderResponse.msg || '订单创建失败')
    }

    const outTradeNo = createOrderResponse.data.orderId
    currentOrderId.value = outTradeNo
    currentAmount.value = totalAmount

    const qrCodeResponse = await axios.get('http://localhost:20002/product/api/payment/qr-code', {
      params: {
        ordersId: outTradeNo,
        totalAmount,
        subject,
        body
      }
    })

    if (qrCodeResponse.data.code === 1) {
      isSandbox.value = qrCodeResponse.data.data.isSandbox || false
      showQrCodeDialog.value = true

      nextTick(() => {
        generateQrCode(qrCodeResponse.data.data.qrCodeUrl)
      })

      startPaymentPolling(outTradeNo)
    } else {
      throw new Error(qrCodeResponse.data.msg || '获取支付二维码失败')
    }
  } catch (error) {
    console.error('支付错误:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '支付失败')
  } finally {
    isProcessing.value = false
  }
}
</script>

<style scoped>
.payment-container {
  padding: 10px;
}

.address-section {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
  cursor: pointer;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.address-header .title {
  font-weight: bold;
}

.address-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.address-detail {
  color: #666;
  font-size: 14px;
}

.address-empty {
  color: #f56c6c;
  text-align: center;
  padding: 10px;
}

.order-section {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.order-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.order-total {
  text-align: right;
  font-weight: bold;
  padding-top: 10px;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.payment-section {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
}

.payment-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.payment-methods {
  display: flex;
  gap: 15px;
}

.payment-method {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
  width: 100px;
}

.payment-method.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.method-icon img {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.method-name {
  margin-top: 5px;
  font-size: 14px;
}

.payment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.payment-amount {
  font-size: 16px;
   text-align: left !important; /* 添加!important提升优先级 */;
}

.payment-amount .amount {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.payment-actions {
  display: flex;
  gap: 12px;
}


.amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.address-list-container {
  padding: 15px;
}

.address-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.address-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.check-icon {
  color: #409eff;
  font-size: 20px;
}

.address-actions {
  margin-top: 20px;
  text-align: center;
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}

.qr-code-canvas {
  width: 200px;
  height: 200px;
  margin-bottom: 15px;
  border: 1px solid #eee;
  padding: 5px;
}

.qr-code-info {
  text-align: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.qr-code-info p {
  margin: 5px 0;
}

.sandbox-tip {
  color: #f56c6c;
  font-size: 12px;
}

.payment-instruction {
  margin-top: 10px;
  color: #666;
  font-size: 12px;
  text-align: center;
}
</style>